import React, { Component } from 'react';
import "../home/home.less";
import { meshLog, SPRemove, SPGet, SPSet } from "../../config";
import Group from "./group/group";
import PubSub from 'pubsub-js'
import EnergyCard from "./energyCard/energyCard";
import EnergyChart from "./energyChart/energyChart";
import {
  getlghtbygroupId, getPidImage,
  saveGroupInfor,
} from '../../utils/homeUtils';
import kong from '../../static/pid/kong.png'
import wifi from '../../static/pid/device_sig_5.png'
import dongle from '../../static/pid/dongle.png'
import emergency from '../../static/pid/emergency_power_supply_gold.png'
import devices from '../../static/pid/devices.png'
import gateway from '../../static/pid/gateway.png'
import jiliangshebei from '../../static/pid/jiliangshebei.png'
import remocon from '../../static/pid/remocon.png'
import sensor from '../../static/pid/sensor.png'
import eye from '../../static/pid/eye.png'
import axios from 'axios';
import { decryptByAes256CBC } from '../admin/jiemi';

import {
  isHightLightDevice,
  isSensorDevice, isJiliangshebeiDevice,
  isPowerDevice, isGatewayDevice, isRemoconDevice,
  isDongleDevice, isNoneDevice
} from '../../utils/pidUtils';

import {
  sumHexBytes, transIntToHex4Str, getOctets2Msg,
  bigEndianToLittleEndian
} from '../../utils/dataUtils'
import { CopySlash, TheaterIcon } from 'lucide-react';

class Home extends Component {
  constructor(props) {
    super(props);
    this.state = {
      // 下拉框选项数据
      dropdownOptions: {
        brand: [],
        area: [],
        zone: [],
        group: [],
        sensor: [],
      },

      // 当前选中值
      selected: {
        brand: '',
        area: '',
        zone: '',
        group: '',
        sensor: '',
      },

      buildingList: [],
      groupList: [],
      zoneList: [],
      meshList: [],
      selectedbuilding: '',
      selectedgroupList: '',
      selectedzoneList: '',
      selectedmeshList: '',
      activeTab: 'sensor',
      groupInfo: '',
      groupDevices: '',
      image: '',
      groupkey: 0,
    };
  }

  componentDidMount() {

    meshLog('home渲染第一步',);
    const buildingList = JSON.parse(SPGet("buildingList"))
    const meshList = JSON.parse(SPGet("meshList"))
    const zoneList = JSON.parse(SPGet("zoneList"))
    const groupList = JSON.parse(SPGet("groupList"))
    const image = JSON.parse(SPGet("image"))
    const changemeshlist = JSON.parse(SPGet("changemeshlist"))
    meshLog('image', image);
    meshLog('buildingList', buildingList);
    meshLog('groupList', groupList);
    meshLog('zoneList', zoneList);
    meshLog('meshList', meshList);

    let isSelected = buildingList.find(item => item.isSelected == 1)

    this.setState({
      buildingList: buildingList,
      groupList: groupList,
      zoneList: zoneList,
      meshList: meshList,
      selectedbuilding: isSelected.buildingName,
      selectedmeshList: changemeshlist == 0 ? meshList[0].meshName : changemeshlist,
      selectedzoneList: zoneList[0].name,
      selectedgroupList: groupList[0].name,
      groupInfo: groupList[0],
      image: image
      // groupDevices: groupDevices,
    })
    this.getGroupdevices(groupList[0].name)
    // 模拟获取数据
    const dropdownOptions = {
      sensor: ['Sensor Control', 'Emergency Control'],
    };

    const selected = {
      sensor: dropdownOptions.sensor[0],
    };
    this.setState({ dropdownOptions, selected });
  }

  getGroupdevices = (groupName) => {
    //查询属于这个groupID的 device
    const groupList = JSON.parse(SPGet("groupList"))
    let groupOneInfo = groupList.find(item => item.name == groupName)
    meshLog('groupOneInfo', groupOneInfo);
    meshLog('groupOneInfo', groupList[0]);
    let groupDevices = getlghtbygroupId(groupOneInfo.groupID)
    meshLog('deviceSet', groupDevices);
    let groupkey = this.state.groupkey
    this.setState({
      groupDevices: groupDevices,
      groupInfo: groupOneInfo,
      groupkey: groupkey + 1,
      selectedgroupList: groupOneInfo.name,
    })
  }

  handleDropdownChange = (key, event) => {
    const value = event.target.value;
    this.setState(
      (prevState) => ({
        selected: {
          ...prevState.selected,
          [key]: value,
        },
      }),
      () => {
        console.log(`你选择的 ${key} 是：${value}`);
      }
    );
  };

  handleTabChange = (tab) => {
    this.setState({ activeTab: tab });
  };

  buildingChange = (key, event) => {
    const value = event.target.value;
    console.log(`你选择的 ${key} 是：${value}`);
  };

  meshListChange = (key, event) => {
    const value = event.target.value;
    console.log(`你选择的 ${key} 是：${value}`);
    const meshList = JSON.parse(SPGet("meshList"))
    let ismeshlist = meshList.find(item => item.meshName == value)
    meshLog('ismeshlist', ismeshlist);

    const dUrl = ismeshlist.profile
    //meshLog('dUrl', dUrl);
    axios.get(dUrl)
      .then(async (value) => {
        //meshLog('admin235value', value.data);
        const hex_key = ismeshlist.meshUUID + "3a8f1c7d0b9e2a4f6c5d0e1f2a3b4c5d"
        const decryptedString = decryptByAes256CBC(hex_key, value.data)
        const jsonData = JSON.parse(decryptedString);
        //meshLog('jsonData', jsonData);//拿到需要解析的所有数据
        const zoneList = jsonData.zoneList
        const groupList = jsonData.groupList
        const nodes = jsonData.nodes
        let wangguan = nodes.find(item => item.pid == '4100')
        meshLog('wangguan', wangguan);
        //如果没有网关，这边需要做个判断
        if (wangguan) {
          SPSet("wangguan", JSON.stringify(wangguan))
        } else {
          wangguan = { 'macAddress': '1234567890' }
          SPSet("wangguan", JSON.stringify(wangguan))
        }
        meshLog('wangguan', wangguan);
        SPSet("image", JSON.stringify(ismeshlist.image))
        SPSet("groupList", JSON.stringify(groupList))
        SPSet("zoneList", JSON.stringify(zoneList))
        SPSet("nodes", JSON.stringify(nodes))
        SPSet("changemeshlist", JSON.stringify(ismeshlist.meshName))
        this.setState({
          groupList: groupList,
          zoneList: zoneList,
          selectedmeshList: ismeshlist.meshName,
          selectedzoneList: zoneList[0].name,
          selectedgroupList: groupList[0].name,
          groupInfo: groupList[0],
          image: ismeshlist.image,
          // groupDevices: groupDevices,
        })
        this.getGroupdevices(groupList[0].name)


      })
      .catch((resaon) => {
        meshLog(resaon);
      })


  };

  zoneListChange = (key, event) => {
    const value = event.target.value;
    console.log(`你选择的 ${key} 是：${value}`);
    const zoneList = JSON.parse(SPGet("zoneList"))
    const groupList = JSON.parse(SPGet("groupList"))
    let iszoneList = zoneList.find(item => item.name == value)
    meshLog('ismeshlist', iszoneList);
    this.setState({
      selectedzoneList: iszoneList.name,
      selectedgroupList: groupList[0].name,
      groupInfo: groupList[0],
      // groupDevices: groupDevices,
    })
    this.getGroupdevices(groupList[0].name)

  };

  groupListChange = (key, event) => {
    const value = event.target.value;
    console.log(`你选择的 ${key} 是：${value}`);
    this.getGroupdevices(value)
  };

  showHightLight = async (device) => {
    meshLog('devicedevicedevice', device);
    // let mac = device.macAddress;
    let mac = bigEndianToLittleEndian(device.macAddress);
    const wangguan = JSON.parse(SPGet("wangguan"))
    const wangguanmac = bigEndianToLittleEndian(wangguan.macAddress)
    meshLog('mac', mac);
    meshLog('wangguanmac', wangguanmac);
    let data1 = '252517'
    let data2 = '00006100000000000001' + mac + '00640000' + '1B00' + '640A' //64是100的亮度值
    let data3 = sumHexBytes(data2) + '5252'
    let value = data1 + data2 + data3
    var data = '0,' + wangguanmac + ',' + value + ',';

    // //修改数据库中的数据
    // //let groupSetx = saveGroupInfor(item, groupStatusX)
    PubSub.publish('showUpdate', data)//控制mqtt发信息

    // meshLog('data3', data3);  104E2000015A
  }


  render() {
    const { buildingList, meshList, groupList, zoneList, selectedbuilding, selectedmeshList, selectedzoneList, selectedgroupList,
      dropdownOptions, selected, activeTab, groupDevices, groupInfo, image } = this.state;

    return (
      <div className="dashboard">
        {/* 左侧部分 */}
        <div className="left-panel">
          {/* 顶部：四个下拉框 */}
          <div className="dropdowns">
            <select
              value={selectedbuilding}
              onChange={(e) => this.buildingChange('brand', e)}>
              {buildingList.map((option) => (
                <option key={option.buildingName}>{option.buildingName}</option>
              ))}
            </select>
            <select
              value={selectedmeshList}
              onChange={(e) => this.meshListChange('area', e)}>
              {meshList.map((option) => (
                <option key={option.meshName}>{option.meshName}</option>
              ))}
            </select>
            <select
              value={selectedzoneList}
              onChange={(e) => this.zoneListChange('zone', e)}>
              {zoneList.map((option) => (
                <option key={option.name}>{option.name}</option>
              ))}
            </select>
            <select
              value={selectedgroupList}
              onChange={(e) => this.groupListChange('group', e)}>
              {groupList.map((option) => (
                <option key={option.name}>{option.name}</option>
              ))}
            </select>
          </div>

          {/* 中间占位区域 */}
          <div className="middle-content">
            {/* <span className="placeholder">此处放置图纸或其他内容</span> */}
            <img src={image} style={{ width: '98%', height: '97%' }} alt="" />
          </div>

          {/* 底部部分 */}
          <div className="bottom-section">
            <EnergyCard></EnergyCard>
            <EnergyChart></EnergyChart>
          </div>
        </div>

        {/* 右侧部分 */}
        <div className="right-panel">
          {/* 上方下拉框 */}
          <div className="sensor-dropdown">
            <select
              value={selected.sensor}
              onChange={(e) => this.handleDropdownChange('sensor', e)}>
              {dropdownOptions.sensor.map((option) => (
                <option key={option}>{option}</option>
              ))}
            </select>
          </div>

          {/* 切换按钮 */}
          <div className="tab-switch">
            <button
              className={activeTab === 'sensor' ? 'active' : ''}
              onClick={() => this.handleTabChange('sensor')}>
              Sensor Settings
            </button>
            <button
              className={activeTab === 'devices' ? 'active' : ''}
              onClick={() => this.handleTabChange('devices')}>
              Devices
            </button>
          </div>

          {/* 内容区 */}

          {
            selected.sensor == 'Sensor Control' ? (
              <div className="tab-content">
                {activeTab === 'sensor' ? (
                  <div className="sensor-settings">
                    <h3>Sensor Settings{ }</h3>
                    <Group groupInfo={groupInfo} key={this.state.groupkey} ></Group>
                  </div>
                ) : (
                  <div className="device-list">
                    <h3>Devices List</h3>
                    {groupDevices.map((device, i) => (
                      <div className="device-item" key={i}>
                        <img alt="" style={{ width: 32, height: 32, }} src={kong} />
                        <img alt="" style={{ display: isSensorDevice(device.pid) == true ? 'block' : 'none', position: 'absolute', width: 32, height: 32, }} src={sensor} />
                        <img alt="" style={{ display: isJiliangshebeiDevice(device.pid) == true ? 'block' : 'none', position: 'absolute', width: 32, height: 32, }} src={jiliangshebei} />
                        <img alt="" style={{ display: isPowerDevice(device.pid) == true ? 'block' : 'none', position: 'absolute', width: 32, height: 32, }} src={emergency} />
                        <img alt="" style={{ display: isGatewayDevice(device.pid) == true ? 'block' : 'none', position: 'absolute', width: 32, height: 32, }} src={gateway} />
                        <img alt="" style={{ display: isRemoconDevice(device.pid) == true ? 'block' : 'none', position: 'absolute', width: 32, height: 32, }} src={remocon} />
                        <img alt="" style={{ display: isDongleDevice(device.pid) == true ? 'block' : 'none', position: 'absolute', width: 32, height: 32, }} src={dongle} />
                        <img alt="" style={{ display: isNoneDevice(device.pid) == true ? 'block' : 'none', position: 'absolute', width: 32, height: 32, }} src={devices} />
                        <span style={{ width: 200, height: 32, position: 'absolute', left: 80, marginTop: 7 }}>{device.name}</span>
                        <img alt="" style={{ display: isHightLightDevice(device.pid) == true ? 'block' : 'none', width: 32, height: 32, position: 'absolute', right: 70, }} onClick={() => { this.showHightLight(device) }} src={eye} />
                        <img alt="" style={{ width: 32, height: 32, }} src={wifi} />
                      </div>
                    ))}
                  </div>
                )}
              </div>
            ) : (<div className="tab-content">
              {activeTab === 'sensor' ? (
                <div className="sensor-settings">
                  <h3>Emergency Control</h3>

                </div>
              ) : (
                <div className="device-list">
                  <h3>Devices(s)</h3>
                  {groupDevices.map((device, i) => (
                    <div className="device-item" key={i}>
                      <span>{device.name}</span>
                      <span>📶</span>
                    </div>
                  ))}
                </div>
              )}
            </div>)
          }



        </div>
      </div>
    );
  }
}

export default Home;
